package com.ins1st.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@Component
public class SqlRunUtil {

    @Value("${spring.datasource.driver-class-name}")
    private String driverCLassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;

    private static final Logger log = LoggerFactory.getLogger(SqlRunUtil.class);

    /**
     * 执行sql脚本文件，使用Spring工具类
     */
    public void runClassPathSql(String classpathFileName, String dbName) {
        try {
            String oldName = getDbName(url);
            Class.forName(driverCLassName);
            Connection conn = DriverManager.getConnection(url.replace(oldName, "ins1st_" + dbName), userName, password);
            ClassPathResource classPathResource = new ClassPathResource(classpathFileName);
            EncodedResource encodedResource = new EncodedResource(classPathResource, "utf-8");
            ScriptUtils.executeSqlScript(conn, encodedResource);
        } catch (Exception e) {
            log.error("执行sql错误！", e);
            throw new RuntimeException("执行sql错误！");
        }

    }

    /**
     * 创建数据库
     *
     * @author fengshuonan
     * @Date 2019-06-18 15:29
     */
    public void createDatabase(String dbName) {
        try {
            Class.forName(driverCLassName);
            Connection conn = DriverManager.getConnection(url, userName, password);
            String oldName = getDbName(url);
            //创建sql
            String sql = "CREATE DATABASE IF NOT EXISTS ins1st_" + dbName + " DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            int i = preparedStatement.executeUpdate();
            log.info("创建数据库！数量：" + i);
        } catch (Exception ex) {
            log.error("创建数据库出现问题！", ex);
        }
    }

    private String getDbName(String url) {
        int first = url.lastIndexOf("/") + 1;
        int last = url.indexOf("?");
        return url.substring(first, last);
    }

}
